package cn.edu.zzuli.nothinglink.controller;


import cn.edu.zzuli.nothinglink.anno.CurrentUser;
import cn.edu.zzuli.nothinglink.constant.WorkConst;
import cn.edu.zzuli.nothinglink.entity.R;
import cn.edu.zzuli.nothinglink.entity.Work;
import cn.edu.zzuli.nothinglink.service.WorkService;
import cn.edu.zzuli.nothinglink.vo.WorkInfoVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author suzyyy
 * @since 2021-04-08
 */
@RestController
@RequestMapping("/work")
public class WorkController {

    @Autowired
    WorkService workService;

    @PostMapping("/info")
    public R createWork(@RequestBody @Valid WorkInfoVo vo, @CurrentUser Integer uId) {
        if (vo.getContentType() == WorkConst.CONTENT_TEXT.Value()
                && StringUtils.isEmpty(vo.getContent())) {
            return R.error().add("error", "题干内容文本不能为空");
        }else if (vo.getContentType() == WorkConst.CONTENT_IMG.Value()
                && StringUtils.isEmpty(vo.getWorkImgUrl())) {
            return R.error().add("error", "图片不能为空");
        }
        return workService.createWork(vo, uId);
    }

    @GetMapping("/info/{workId}")
    public R getWorkInfo(@PathVariable Integer workId) {
        Work w = workService.getWorkInfoById(workId);
        if (w != null) return R.success().add("work", w);
        return R.error().add("error", "该作业不存在");
    }

    @PutMapping("/info")
    public R updateWork(@RequestBody @Valid WorkInfoVo vo) {
        return workService.updateTheWork(vo);
    }

    @GetMapping("/info/course/{courseId}")
    public R getTheCourseWorks(@PathVariable Integer courseId) {
        return workService.getWorksInTheCourse(courseId);
    }

    @GetMapping("/in/myclass/{type}")
    public R getMyWorks(@CurrentUser Integer stuId, @PathVariable String type) {
        if (stuId == null) return R.error().add("error", "请先登录");
        return workService.getWorksInMyClass(stuId, type);
    }

    @GetMapping("/in/course/{courseName}")
    public R getCourseWorks(@PathVariable String courseName) {
        return workService.getWorksInCourseByCourseName(courseName.trim());
    }

    @PostMapping("/submit")
    public R submitWork(@CurrentUser Integer stuId, @RequestBody JSONObject json) {
        if (stuId == null) return R.error().add("error", "请先登录");
        if (json.get("contentType") == null || json.get("workId") == null )
            return R.error().add("error", "请检查参数");

        return workService.submitWorkRecord(stuId, json);
    }

    @GetMapping("/record/in/{workId}")
    public R getWorkSubmitRecord(@PathVariable Integer workId) {
        return workService.getWorkSubmitRecordByWorkId(workId);
    }

}

